package top.songxs.yygh.oss.service.service.impl;

import com.aliyun.oss.OSS;
import com.aliyun.oss.OSSClientBuilder;
import org.joda.time.DateTime;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import top.songxs.yygh.oss.service.constant.ConstantPropertiesUtil;
import top.songxs.yygh.oss.service.service.FileService;

import java.io.InputStream;
import java.util.UUID;
@Service
public class FileServiceImpl implements FileService {
    @Override
    public String upload(MultipartFile file) {
        //获取oss服务所需的四个基本参数
        String endPoint = ConstantPropertiesUtil.END_POINT;
        String accessKeyId = ConstantPropertiesUtil.ACCESS_KEY_ID;
        String accessKeySecret = ConstantPropertiesUtil.ACCESS_KEY_SECRET;
        String bucketName = ConstantPropertiesUtil.BUCKET_NAME;

        //创建ossClient实例
        OSS ossClient = new OSSClientBuilder().build(endPoint, accessKeyId, accessKeySecret);
        try {

            //构建一个输入流
            InputStream inputStream = file.getInputStream();
            //获取传来的文件名
            String fileName = file.getOriginalFilename();
            //随机生成一个uuid拼接到文件名中来保证文件名唯一
            String uuid = UUID.randomUUID().toString().replace("-", "");
            fileName = uuid + fileName;
            //按照日期进行文件分别存储  文件路径拼接当前时间
            String timeUrl = new DateTime().toString("yyyy/MM/dd");
            fileName = timeUrl + "/" + fileName;
            //OssClient 执行上传
            ossClient.putObject(bucketName, fileName, inputStream);


            //上传之后的文件url返回
            //https://yygh-atguigu.oss-cn-beijing.aliyuncs.com/01.jpg
            //后续存入数据库中
            String url = "https://" + bucketName + "." + endPoint + "/" + fileName;
            return url;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }finally {
            ossClient.shutdown();
        }


    }
}
